<template>
  <div class="register-container">
    <el-form
      :model="registerForm"
      :rules="rules"
      ref="registerForm"
      label-width="80px"
      class="max-width-form register-form"
    >
      <h2>用户注册</h2>

      <!-- 用户名 -->
      <el-form-item label="用户名" prop="username">
        <el-input v-model="registerForm.username" placeholder="请输入用户名"></el-input>
      </el-form-item>

      <!-- 密码 -->
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="registerForm.password" show-password placeholder="请输入密码"></el-input>
      </el-form-item>

      <!-- 真实姓名 -->
      <el-form-item label="真实姓名" prop="realName">
        <el-input v-model="registerForm.fullName" placeholder="请输入真实姓名"></el-input>
      </el-form-item>

      <!-- 特长 -->
      <el-form-item label="特长" prop="skills">
        <el-select v-model="registerForm.skillIdList" 
          multiple placeholder="请选择您的特长（最多选3项）" 
          style="width: 100%">
          <el-option
            v-for="skill in skills"
            :key="skill.skillId"
            :label="skill.skillName"
            :value="skill.skillId">
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 邮箱 -->
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="registerForm.email" placeholder="请输入邮箱地址"></el-input>
      </el-form-item>

      <!-- 电话号码 -->
      <el-form-item label="电话号码" prop="phone">
        <el-input v-model.number="registerForm.phone" placeholder="请输入电话号码"></el-input>
      </el-form-item>


      <!-- 身份 -->
      <el-form-item label="身份" prop="role">
        <el-select v-model="registerForm.roleId" placeholder="请选择身份" style="width: 100%">
            <el-option
              v-for="role in roles"
              :key="role.id"
              :label="role.name"
              :value="role.id">
            </el-option>
        </el-select>
      </el-form-item>

      <!-- 注册按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitRegister('registerForm')">注册</el-button>
        <el-button @click="goToLogin">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { register, getSkills } from '@/api/user'; // 引入 getSkills 接口

export default {
  data() {
    return {
      registerForm: {
        username: '',
        password: '',
        email: '',
        phone: '',
        fullName: '',
        roleId: null,
        skillIdList: [] 
     },
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 8, message: '密码长度不能小于8位', trigger: 'blur' }
        ],
        fullName: [
          { required: true, message: '真实姓名不能为空', trigger: 'blur' }
        ],
        skillIdList: [
          { 
            required: true, 
            message: '请选择您的特长（最多选3项）', 
            trigger: 'change'
          },
          {
            validator: (rule, value, callback) => {
              if (value.length > 3) {
                callback(new Error('最多只能选择3个特长'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
        ],
        phone: [
          { required: true, message: '电话号码不能为空', trigger: 'blur' },
          { type: 'number', message: '电话号码必须为数字', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择身份', trigger: 'change' }
        ]
      },
      roles: [
        {id: 0, name: '志愿者'},
        {id: 1, name: '管理员'}
      ],
      skills: [] // 初始化为空数组
    };
  },
  async mounted() {
    try {
      const response = await getSkills();
      console.log('获取技能列表成功:', response.data);
      this.skills = response.data.map(skill => ({
        skillId: skill.skillId,
        skillName: skill.skillName,
        createdAt: skill.createdAt
      }));
      console.log('技能列表:', this.skills);
    } catch (error) {
      console.error('获取技能列表失败:', error);
      this.skills = [];
    }
  },
  methods: {
    async submitRegister(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            const response = await register(this.registerForm);
            console.log('注册成功！响应:', response);

            // 提取 token 并存入 localStorage
            const token = response.data?.token;
            if (token) {
              localStorage.setItem('token', token);
            }

            this.$message.success('注册成功！');
            setTimeout(() => {
              this.$router.push('/login');
            }, 500);
          } catch (error) {
            console.error('注册失败:', error);
            this.$message.error('注册失败，请重试或联系管理员');
          }
        } else {
          console.log('表单验证失败');
          this.$message.error('请检查输入信息是否正确');
          return false;
        }
      });
    },
    goToLogin() {
        this.$router.push('/login');
    }
  }
};
</script>

<style scoped>
.max-width-form {
  max-width: 600px; /* 将最大宽度调整为600px */
  margin: auto;
}

.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
}

.register-form {
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

</style>
